<?php
/**
 * 静态化类
 * 
 */
class StaticD {
    public $memObj;
	private $_config = array();
	private $_instance;
	private $_routeConfig;
	private $_cityPinyin;
	public $varnishCleanPath = '/cache/varnishclean';
	public $baseCachePath = '/cache';
	public $maxFilesOn1Dir = 10000;//单个目录存放的最大文件数
	public $memKeyPrefix = 'static_cache_';
	protected $joinLetter = '_0_'; //
	public $siteParams = array();//yii框架中的params.php配置文件数组
	public $serverType;
	public $staticGetParams = array('utm_source'=>'#');//当这些get参数出现时，也把这次请求归于静态页面请求，"#"代表这个参数的值为任意
	/*public $mainHost = '27.50.133.2';
	public $memServers = array(
                               //array('127.0.0.1', 11214),
		                       array('192.168.1.13', 11215),
                               //array('mem2.domain.com', 11211, 67),
                         );*/

    public function __construct($config){
		//负载均衡下，静态化时，如果是“从服务器”向“主服务器”的请求，则作以下处理
		$_SERVER['HTTP_HOST'] = isset($_COOKIE['dld_static_http_host'])&&$_COOKIE['dld_static_http_host']?$_COOKIE['dld_static_http_host']:$_SERVER['HTTP_HOST'];
        $this->_config = $config;
	}

    public function initMem(){
        $m = new Memcached();
		$siteParams = $this->getSiteParams();
        $servers = $siteParams['staticMemServers'];
        $m->addServers($servers);
		$this->memObj = $m;
	}

	public function getMem(){
        if($this->memObj === null){
            $this->initMem();
		}
		return $this->memObj;
	}

	public function getInstance($config){
        if($this->_instance == NULL){
            $this->_instance = new StaticD($config);   
		}

		return $this->_instance;
	}

	public function getSiteParams(){
        if(empty($this->siteParams)){
            $this->siteParams = require(dirname(__FILE__) . '/../config/params.php');
		}

		return $this->siteParams;
	}

	public function getServerType(){
        if(empty($this->serverType)){
			if(file_exists(dirname(__FILE__) . '/../config/serverType.php')){
                $this->serverType = require(dirname(__FILE__) . '/../config/serverType.php');
			}
			else{
                $this->serverType = 'slave';
			}
		}

		return $this->serverType;
	}

    public function getUri(){
        /*$map =  array(
              '/meishi'=>array('r'=>'topic/index/index','cat_code'=>'101','uri'=>'/topic/index/index/#city#_0_101.html'),
			  '/zhusu'=>array('r'=>'topic/index/index','cat_code'=>'104','uri'=>'/topic/index/index/#city#_0_104.html'),
			  '/gouwu'=>array('r'=>'topic/index/index','cat_code'=>'102','uri'=>'/topic/index/index/#city#_0_102.html'),
              );*/
        $requestUri = $_SERVER['REQUEST_URI'];
        /*if(isset($map[$requestUri])){
			$pinyin = $this->getDomainCityPinyin();
			$_GET = array_merge($_GET,$map[$requestUri]);
			$requestUri = strtr($map[$requestUri]['uri'],array('#city#'=>$pinyin));
		}*/
		return $requestUri;
       // return $_SERVER['REQUEST_URI'];
	}

	public function parseRoute($uri){

	}

    public function displayCache(){
		$return = false;
        $routeConfig = $this->getRouteConfig();
		$cityPinyin = $this->getDomainCityPinyin();
		if($cityPinyin == 'www' && $this->getUri() == '/'){
            return false;
		}
		//if($routeConfig && $cityPinyin != 'www'){
        if($routeConfig){
			if($routeConfig['sta'] == '0' || $routeConfig['is_fake_static'] == '1'){
                $this->staticToDynamic();
				return false;
			}
		    $path = $key = $this->getStaticUri();
			if($path){
				$routeConfig['is_mem'] = false;// 暂时屏蔽掉memcache缓存
		        if($routeConfig['is_mem']){
                    if($this->displayMem($key)){
				        $return = true;
			        }
		        }
		        if(!$return){
					$siteParams = $this->getSiteParams();
					$serverType = $this->getServerType();
			        $path = str_replace('//','/',$_SERVER['DOCUMENT_ROOT'].'/'.$path);
                    if($this->displayFile($path,$routeConfig['cache_time'])){
		                if($serverType == 'main' && $routeConfig['is_mem']){
					        $cacheTime = !intval($routeConfig['cache_time'])?0:$routeConfig['cache_time'] - (time()-filemtime($path));
		                    $m = $this->getMem();
		                    $m->set($this->memKeyPrefix.md5($key),file_get_contents($path),$cacheTime);                      
		                }
                        $return = true;
			        }
		        }
		        if(!$return){
			        if($serverType == 'main'){
                        $this->staticToDynamic();
						//var_dump($_SERVER['REQUEST_URI']);exit;
						//var_dump($_GET);
							//var_dump($_SERVER['REQUEST_URI']);exit;
			        }
			        else{
						$httpHost = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'';
						if($httpHost){
							$uri = $this->getUri();
							$mainHost = isset($siteParams['mainHost'])?$siteParams['mainHost']:'';
                            $url = 'http://'.$mainHost.$uri;
                            $ch = curl_init();
                            curl_setopt ($ch,CURLOPT_URL,$url);
                            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
                            curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1');
                            curl_setopt($ch,CURLOPT_COOKIE,'dld_static_http_host='.$httpHost);
                            $res = curl_exec($ch);
                            curl_close ($ch);
                            echo $res;
					    }
				        exit;
			        }
		        }
			}
		}

		return $return;
	}

    public function displayFile($path,$expireTime = 0){
		$return = false;
		if(file_exists($path)){
			$expireTime = intval($expireTime);
            if($expireTime === 0 || (time() - filemtime($path) <= $expireTime)){
				$return = true;
                require($path);
			}else{
                unlink($path);
			}
		}
		return $return;
	}

    public function displayMem($key){
		//$routeConfig = $this->getRouteConfig();
		$m = $this->getMem();
		$content = $m->get($this->memKeyPrefix.md5($key));
		if($content){
            echo $content;
			return true;
		}
        return false;
	}

    /*
	*获取当前请求的路由静态配置信息,仅当静态url时有效
	*/
    public function getRouteConfig(){
		if($this->_routeConfig === null){
            $uri = $this->getUri();
            $staticRoute = $this->getRouteForStaticUri($uri);
		    $this->_routeConfig = $staticRoute&&isset($this->_config[$staticRoute])?$this->_config[$staticRoute]:false;
		}

		return $this->_routeConfig;
	}

    /*
	*获取当前静态请求的路由,仅对静态url有效
	*/
	public function getRouteForStaticUri($uri){
		//判断如果请求为静态，则做相应处理
		if($this->staticJudge($uri)){
			$markPos = strpos($uri,'?');
			if($markPos !== false){
                $uri = substr($uri,0,$markPos);
			}

			if(strpos($uri,$this->baseCachePath) === 0){
                $uri = substr($uri,strlen($this->baseCachePath));
			}
			if($uri == '/'){
                return 'index';
		    }
			else{
		        $tmp = explode('/',$uri);
			    $routeAry = array();
			    foreach($tmp as $val){
                    if($val){
                        $routeAry[]=$val;
                        if(count($routeAry) >= 3){
						    break;
					    }
				    }
			    }
                while(count($routeAry)){
				    $r = implode('/',$routeAry);
                    if(isset($this->_config[$r])){
                        return $r;
				    }
				    array_pop($routeAry);
			    }
			}
		}
		return false;
	}
    
	/*
	*对当前请求是否属于静态请求进行判断
	*@return  boolean 是静态返回 true,反之 返回false
	*/
    public function staticJudge($uri){
		$flag = false;
		//带get参数，并且在$this->staticGetParams中匹配不上的，一律判断为请求为动态;否则为请求为静态
		$posMark = strpos($uri,'?');
		$hpostMark = strpos($uri,'.html');
		if($posMark === false || ($hpostMark !== false && $hpostMark < $posMark)){
            $flag = true;
		}
		else if(!isset($_GET['r'])){            
            foreach($this->staticGetParams as $key=>$val){
                $flag = isset($_GET[$key])&&($val=='#'||$val==$_GET[$key]);
				if($flag)
					break;
			}
		}

		return $flag;
	}

    public function getDomainCityPinyin(){
		if($this->_cityPinyin === NULL){
		    if(isset($_SERVER['HTTP_HOST'])){
			    $domain = $_SERVER['HTTP_HOST'];
		    }
		    else
		    {
			    $domain=$_SERVER['SERVER_NAME'];
		    }
		    $tmp = explode('.',$domain);
		    $this->_cityPinyin = isset($tmp[0])?$tmp[0]:false;
		}
		return $this->_cityPinyin;
	}

    public function getHttpHost(){
		if(isset($_SERVER['HTTP_HOST'])){
			$domain = $_SERVER['HTTP_HOST'];
		}
		else
		{
			$domain=$_SERVER['SERVER_NAME'];
		}
		return $domain;
	}

    /*
	*获取当前请求的静态uri
	*@param int $operateType 1表示展示，2表示写入
	*/
    public function getStaticUri($params = array(),$operateType = 1){
        $routeConfig = $this->getRouteConfig();
		$staticUri = '';
		$cityPinyin = $this->getDomainCityPinyin();
		//如果访问大首页，直接返回空字符串
		if($cityPinyin == 'www' && $this->getUri() == '/'){
            return '';
		}
        //if($routeConfig && $cityPinyin != 'www'){
        if($routeConfig){
		    $basePath = $routeConfig['path']?$routeConfig['path']:$this->baseCachePath;
            $staticUri .= $basePath.'/'.$routeConfig['route'];
		    switch($routeConfig['page_type']){
                case '1':
				    if(strpos($staticUri,'.php') === false){
			            if($routeConfig['is_sub_site']){
                            $staticUri .= '/'.$cityPinyin.'.html';  
				        }
			            else{ 
                            $staticUri .= '/index.html';
				        }
			        }
				    break;
                case '2':
				    if(strpos($staticUri,'.php') === false){
			            if($routeConfig['is_sub_site']){
                            $staticUri .= '/'.$cityPinyin.'.index.html';  
				        }
			            else{
                            $staticUri .= '/index.html';
				        }
			        }
				    break;
                case '4':
				    //如果是写入时
				    if($operateType == 2){
			            if($routeConfig['params']){
						    if(trim($routeConfig['sub_path_param'])){
					            $pathParam = isset($params[$routeConfig['sub_path_param']])?intval($params[$routeConfig['sub_path_param']]):0;
                                $dirNum = floor($pathParam/$this->maxFilesOn1Dir);
						        $staticUri .= '/'.$dirNum;
						    }
                            /*$p = explode(',',$routeConfig['params']); 
					        $pn = trim($p[0]);
					        if(isset($params[$pn]) && $params[$pn]){
                                $staticUri .= '/'.$params[$pn].'.html'; 
					        }*/
							//var_dump($params);exit;
							$fileName = $this->genFileName($params,$routeConfig,4,true);
							if($fileName){
						        if($routeConfig['is_sub_site']){
                                    $fileName = $cityPinyin.$this->joinLetter.$fileName;
						        }
                                $staticUri .= '/'.$fileName;
							}
				        }
			        }
				    else{
                        if(trim($routeConfig['sub_path_param'])){
                            $scriptName = $this->getStaticScriptName($this->getUri(),2);
                        }
						else{
                            $scriptName = $this->getStaticScriptName($this->getUri());
						}
						/*if($routeConfig['is_sub_site']){
                            $scriptName = $cityPinyin.$this->joinLetter.$scriptName;
						}*/
                        $staticUri .= '/'.$scriptName;
						#echo $staticUri;exit;
				    }
				    break;
                case '3':
				    //如果是写入时
				    if($operateType == 2){
			            if($routeConfig['params']){
						    if(trim($routeConfig['sub_path_param'])){
					            $pathParam = isset($params[$routeConfig['sub_path_param']])?intval($params[$routeConfig['sub_path_param']]):0;
                                $dirNum = floor($pathParam/$this->maxFilesOn1Dir);
						        $staticUri .= '/'.$dirNum;
						    }
                            $p = explode(',',$routeConfig['params']); 
					        $pn = trim($p[0]);
					        if(isset($params[$pn]) && $params[$pn]){
                                $staticUri .= '/'.$params[$pn].'.html'; 
					        }
				        }
			        }
				    else{
                        $scriptName = $this->getStaticScriptName($this->getUri());
                        $staticUri .= '/'.$scriptName;
				    }
				    break;
		    }        
		}

		return str_replace(array('///','//'),array('/','/'),$staticUri);
	}

    public function writeCacheFile($content,$params = array(),$overwrite = true){
        $path = $this->getStaticUri($params,2);
        if($path){
		    $path = str_replace('//','/',$_SERVER['DOCUMENT_ROOT'].'/'.$path);
			$pos = strrpos($path,'/');
			$dirExist = true;
			if($pos !== false){
			    $dir = substr($path,0,$pos);
				if($dir){
				    if(!file_exists($dir)){
                        if(!mkdir($dir,0777,true)){
                            $dirExist = false;
					    }
				    }
				}
				else{
                    $dirExist = false;
				}
			}
			else{
                $dirExist = false;
			}
			if($dirExist){
		        if($overwrite){
                    file_put_contents($path,$content);
		        }
		        else{
                    if(!file_exists($path)){
                        file_put_contents($path,$content);
			        }
		        }
			}
		}
	}

	public function writeCacheMem($content,$params = array(), $expireTime = 0, $overwrite = true){
        $key = $this->getStaticUri($params,2);
        if($key){
			$key = $this->memKeyPrefix.md5($key);
			$m = $this->getMem();
            if($m->get($key)){
			   if($overwrite){
				   $m->set($key,$content,$expireTime);   
			   }
			}
			else{
                $m->set($key,$content,$expireTime);
			}
		}
	}

    public function writeCache($content,$params = array(),$overwrite = true){
        $routeConfig = $this->getRouteConfig();
		if($routeConfig['is_fake_static'] != '1'){
		    if($routeConfig && $routeConfig['is_mem']){
                $this->writeCacheMem($content,$params,intval($routeConfig['cache_time']), $overwrite);
		    }
		    $this->writeCacheFile($content,$params, $overwrite);
		}
	}

    public function genStaticUrl($url){
        $params = $this->parseParamsFromUrl($url);
		if(empty($params) || !isset($params['r'])){
            $route = 'index';
		}
		else{
            $route = trim($params['r'],' /');
		}
        $routeConfig = $route&&isset($this->_config[$route])?$this->_config[$route]:false;
		if($routeConfig && $routeConfig['sta']){
			$routeConfig['short_route'] = trim($routeConfig['short_route']);
			$uriPath =  $routeConfig['short_route']?$routeConfig['short_route']:trim($routeConfig['route']); 		
		    $domain = $routeConfig['domain']?'http://'.$routeConfig['domain']:''; 
		    switch($routeConfig['page_type']){
                case '1':
					$url = $domain.'/'.$uriPath; 
				    if($routeConfig['short_route'] && $routeConfig['short_route'] != '/'){
					    $url .= '/';	
					}
				    break;
                case '2':
					$url = $domain.'/'.$uriPath; 
				    if($routeConfig['short_route'] && $routeConfig['short_route'] != '/'){
					    $url .= '/';	
					}
				    break;
                case '4':
                    $fileName = $this->genFileName($params,$routeConfig,4);
					if($fileName){
						if($routeConfig['is_sub_site']){
							$cityPinyin = $this->getDomainCityPinyin();
                             $fileName = $cityPinyin.$this->joinLetter.$fileName;
						}
			            if(!empty($routeConfig['is_real_static'])){
                            $uriPath = $this->baseCachePath . '/' . trim($routeConfig['route']);
			            }
					    $routeConfig['is_sub_path'] = trim($routeConfig['is_sub_path']);
				        $routeConfig['sub_path_param'] = trim($routeConfig['sub_path_param']);
                        if($routeConfig['is_sub_path'] && $routeConfig['sub_path_param']){
					        $pathParam = isset($params[$routeConfig['sub_path_param']])?intval($params[$routeConfig['sub_path_param']]):0;
                            $dirNum = floor($pathParam/$this->maxFilesOn1Dir);
						    $uriPath .= '/'.$dirNum;
				        }
                        $url = $domain.'/'.$uriPath.'/'.$fileName;
					}
				    break;
                case '3':
					if($routeConfig['params']){
					    $url = $domain.'/'.$uriPath;
                        $tmp = explode(',',$routeConfig['params']);
						$fileName = '';
						foreach($tmp as $val){
                            $val = trim($val);
							if(isset($params[$val]) && $params[$val]){
                               $fileName .=  $val.'-'.$params[$val].$this->joinLetter;
							}
						}
						if($fileName){
                            $fileName = substr($fileName,0,-(strlen($this->joinLetter))).'.html';
							$url .= '/'.$fileName;
						}
											//var_dump($url);exit;
				    }
				    break;
		    }
		}
		return str_replace('//','/',$url);
	}
   
    public function parseParamsFromUrl($url){
        $params = array();
		if(strpos($url,'?') !== false){
            list($tmp1,$tmp) = explode('?',$url);
			$_params = trim($tmp)?explode('&',$tmp):array();
			foreach($_params as $val){
				$val = trim($val);
				if($val){
                    $p = explode('=',$val); 
					$params[$p[0]] = isset($p[1])?$p[1]:'';
				}
			}
		}
		return $params;
	}

    public function getRouteFromDynamicUrl($url){
        $params = array();
		if(strpos($url,'?') !== false){
            list($tmp1,$tmp) = explode('?',$url);
			$_params = trim($tmp)?explode('&',$tmp):array();
			foreach($_params as $val){
				$val = trim($val);
				if($val){
                    $p = explode('=',$val); 
					$params[$p[0]] = isset($p[1])?$p[1]:'';
				}
			}
		}
		if(!isset($params['r'])){
            $route = 'index';
		}
		else{
            $route = trim($params['r'],' /');
		}
		return $route;
	}

	public function getRouteConfigFromDynamicUrl($url){
		if($url){
            $route = $this->getRouteFromDynamicUrl($url);
		    return isset($this->_config[$route])?$this->_config[$route]:false;
		}
		return false;
	}

    public function genFileName($params,$routeConfig,$page_type,$test=false){
		$fileName = '';
        if($routeConfig['params']){
            $tmp = explode(',',$routeConfig['params']);
			switch($page_type){
				case '3':
						foreach($tmp as $val){
                            $val = trim($val);
							if(isset($params[$val]) && $params[$val]){
                               $fileName .=  $val.'-'.$params[$val].$this->joinLetter;
							}
						}
						if($fileName){
                            $fileName = substr($fileName,0,-(strlen($this->joinLetter))).'.html';
						}
				break;
				case '4':
					if(count($tmp) > 1){
						foreach($tmp as $val){
                            $val = trim($val);
							if(isset($params[$val]) && $params[$val]){
                               $fileName .=  $val.'-'.$params[$val].$this->joinLetter;
							}
						}
						if($fileName){
                            $fileName = substr($fileName,0,-(strlen($this->joinLetter))).'.html';
						}
				    }else{
                        $val = trim($tmp[0]);
				        $prefix = isset($params[$val])&&$params[$val]?trim($params[$val]):'';
                        $fileName .= $prefix?$prefix.'.html':'';
					}
				break;
			}
		}
		return $fileName;
	}

    public function staticToDynamic(){
		$staticUri = $this->getUri();
		$routeConfig = $this->getRouteConfig();
		if($routeConfig){
            $_GET['r']= $routeConfig['route']; 
		    //$staticUri = $this->getStaticUri();
		    $scriptName = $this->getStaticScriptName($staticUri);
            //var_dump($scriptName);
		    switch($routeConfig['page_type']){
                case '4':
				    if($scriptName){
			            if($routeConfig['is_sub_site']){
				            $cityPinyin = $this->getDomainCityPinyin();
                            $scriptName = str_replace($cityPinyin.$this->joinLetter,'',$scriptName);
			            }
                        $pvs = explode('.',$scriptName);
						$pvs = explode($this->joinLetter,$pvs[0]);
					    if($routeConfig['params']){
                            $pns = explode(',',$routeConfig['params']);
							if(count($pns) > 1){
							    foreach($pvs as $val){
								    if($val){
									    $tmp = explode('-',$val);
					                    $pn = trim($tmp[0]);
						                $pv = isset($tmp[1])?trim($tmp[1]):0;
								        $pn && $_GET[$pn] = $pv;
								    }
							    }
							}
							else{
					            $pn = trim($pns[0]);
						        $pv = trim($pvs[0]);
						        $pn && $_GET[$pn] = $pv;
							}
			            }
			        } 
				    break;
                case '3':
				    if($scriptName){
                        $pvs = explode('.',$scriptName);
						$pvs = explode($this->joinLetter,$pvs[0]);
					    if($routeConfig['params']){
                            //$pns = explode(',',$routeConfig['params']);
							foreach($pvs as $val){
								if($val){
									$tmp = explode('-',$val);
					                $pn = trim($tmp[0]);
						            $pv = isset($tmp[1])?trim($tmp[1]):0;
								    $pn && $_GET[$pn] = $pv;
								}
							}
			            }
			        } 
					//var_dump($_GET);exit;
				    break;
		    }
		}
	}

    public function getStaticScriptName($staticUri,$level = 1){
		$scriptName = '';
        /*$pos = strrpos($staticUri,'/');
		if($pos === false){
            $scriptName = $staticUri;
		}
		else{
            $scriptName = substr($staticUri,$pos+1);
		}*/
		if($staticUri){
		    $tmp = explode('/',$staticUri);
		    $tmp1 = array();
		    while($level > 0 && count($tmp)){
                $tmp2 = array_pop($tmp);
				if($tmp2 !== ''){
                    array_unshift($tmp1,$tmp2);
					$level--;
				}
		    }
	
            $scriptName .= implode('/',$tmp1);
		}
		return $scriptName;
	}

    public function updateCache($path,$route = ''){
		$siteParams = $this->getSiteParams();
		if(isset($siteParams['varnishCache']) && $siteParams['varnishCache']){
            $this->updateVarnishCahce($path,$route);
		}
        $this->updateMemCahce($path);
		$this->updateFileCahce($path);
		if(isset($siteParams['autoGenStatic']) && $siteParams['autoGenStatic']){
		    $routeConfig = isset($this->_config[$route])?$this->_config[$route]:'';
			if($routeConfig){
                if($routeConfig['page_type'] != 3 && $routeConfig['page_type'] != 4 && $routeConfig['is_sub_site']){
					$autoGenStaticUriPath = str_replace(array('///','//'),array('/','/'),$_SERVER['DOCUMENT_ROOT'].'/'.$siteParams['autoGenStaticFile']);
					$uri = $routeConfig['short_route']?'/'.$routeConfig['short_route'].'/':$this->baseCachePath.'/'.$routeConfig['route'];
					$uri = str_replace(array('///','//'),array('/','/'),$uri);
					file_put_contents($autoGenStaticUriPath,$uri."\r\n",FILE_APPEND);
				}
			}
		}
	}

    public function updateMemCahce($path){
		$m = $this->getMem();
		if(is_dir($path)){
            $m->flush();
			return;
		}
		$documentRoot = $_SERVER['DOCUMENT_ROOT'];
		if(strrpos($documentRoot,'/') == strlen($documentRoot)-1){
            $documentRoot = substr($documentRoot,0,strlen($documentRoot)-1);
		}
		$tmp = explode($documentRoot,$path);
		//var_dump($tmp);exit;
		if(isset($tmp[1])){
            $m->delete($this->memKeyPrefix.md5($tmp[1]));
		}
	}

    public function updateFileCahce($path){
		//指定目录的才能更新
		$basePath = str_replace(array('///','//'),array('/','/'),$_SERVER['DOCUMENT_ROOT'].'/'.$this->baseCachePath);
		if(strpos($path,$basePath) === 0){
            if(is_file($path)){
                unlink($path);
		    }
		    elseif(is_dir($path)){
				system('rm -rf '.$path.'/*');
                /*$files = scandir($path); 
			    if($files){
			        array_splice($files,array_search('.',$files),1);
			        array_splice($files,array_search('..',$files),1);
			        array_search('.svn',$files)!==false && array_splice($files,array_search('.svn',$files),1);
				    $path .= substr($path,-1,1) != '/'?'/':'';
				    foreach($files as $val){
                        $this->updateFileCahce($path.$val);
				    }
			    }*/
		    }
		}
	}

    public function updateVarnishCahce($path,$route){
		$siteParams = $this->getSiteParams();
		$varnishPath = str_replace(array('///','//'),array('/','/'),$_SERVER['DOCUMENT_ROOT'].'/'.$siteParams['varnishCleanPath']);
		$routeConfig = isset($this->_config[$route])?$this->_config[$route]:'';
		$banRegExp = '';
		if($routeConfig){
            if(is_file($path)){
				if($routeConfig['page_type'] == 4){
					if($routeConfig['is_real_static']){
                        $banRegExp = '/'.$this->baseCachePath.'/'.$routeConfig['route'];
					}
					else{
                        $banRegExp = $routeConfig['short_route']?'/'.$routeConfig['short_route']:'/'.$routeConfig['route'];
					}
					if($routeConfig['is_sub_path']){
                        $paths = explode('/',$path);
						$count = count($paths);
						if(preg_match("/[0-9]+/",$paths[$count-2])){
						    $banRegExp .= '/'.$paths[$count-2].'/'.$paths[$count-1];
						}
					}
				}
				else{
                    if($routeConfig['short_route']){
                        $banRegExp = '/'.$routeConfig['short_route'];
					}
					else{
                        $banRegExp = '/'.$routeConfig['route'];
					}
				}
		    }
		    else{
				//system('rm -rf '.$path.'/*');
				if($routeConfig['page_type'] == 4){
					if($routeConfig['is_real_static']){
                        $banRegExp = '/'.$this->baseCachePath.'/'.$routeConfig['route'];
					}
					else{
                        $banRegExp = $routeConfig['short_route']?'/'.$routeConfig['short_route']:'/'.$routeConfig['route'];
					}
					if($routeConfig['is_sub_path']){
                        $paths = explode('/',$path);
						$count = count($paths);
                        $x = $paths[$count-1] === ''?$paths[$count-2]:$paths[$count-1];
						if(preg_match("/[0-9]+/",$x)){
                            $banRegExp .= '/'.$x;
						}
						/*if($count > 2){
						    $banRegExp .= $paths[$count-1] === ''?'/'.$paths[$count-2]:'/'.$paths[$count-1];
						}*/
					}
				}
				else{
                    if($routeConfig['short_route']){
						$banRegExp = '/'.$routeConfig['short_route'];
				        if(($routeConfig['page_type'] == 2 || $routeConfig['page_type'] == 1) && $routeConfig['short_route'] != '/'){
					        $banRegExp .= '/$';	
					    }
						else{
                            $banRegExp .= '$';
						}
					}
					else{
                        $banRegExp = '/'.$routeConfig['route'].'$';
					}
				}
		    }
		}
		$banRegExp = str_replace(array('///','//'),array('/','/'),$banRegExp);
        $banRegExp && file_put_contents($varnishPath,$banRegExp."\r\n",FILE_APPEND);

		return true;
	}

    public function getFileList($dir,$page=1,$pageSize=20,$route=''){
		$result = array('count'=>0,'data'=>array());
		if(file_exists($dir)){
            $files = scandir($dir);
		    if($files){
			    array_splice($files,array_search('.',$files),1);
			    array_splice($files,array_search('..',$files),1);
			    array_search('.svn',$files)!==false && array_splice($files,array_search('.svn',$files),1);
			    $result['count'] = count($files);
			    if($page < 1){
                   $page = 1;
			    }
			    $start = ($page - 1) * $pageSize;
			    $end = $page * $pageSize;
			    if($start <= $result['count']){
				    $tmp = array();
				    $dir .= substr($dir,-1,1) != '/'?'/':'';
                    for($i = $start;$i<$end&&$i<$result['count'];$i++){
                        $tmp['name']=  $dir.$files[$i];
					    $tmp['type']=  is_dir($tmp['name'])?'d':'f';
					    $tmp['filemtime']=  date('Y-m-d H:i:s',filemtime($tmp['name']));
					    $result['data'][] = $tmp;
				    }
			    }
		    }
		}
		return $result;
	}

	public function getCacheDirByRoute($r){
        $r = strtolower($r);
		$cacheDir = '';
		$routeConfig = isset($this->_config[$r])?$this->_config[$r]:false;
		if($routeConfig){
		    $path = $routeConfig['path']?$routeConfig['path']:$this->baseCachePath;
            $path .= '/'.$routeConfig['route'];
            $cacheDir = str_replace(array('///','//'),array('/','/'),$_SERVER['DOCUMENT_ROOT'].'/'.$path.'/');
			//$cacheDir = $_SERVER['DOCUMENT_ROOT'].'/'.$path.'/';
		}
		return $cacheDir;
	}

    public function updateCacheOnTime($route,$params = array()){
		$staticUpdateConf = include(Yii::app()->params['staticUpdateConfigPath']);
		if(isset($staticUpdateConf[$route])){
            $updateConf = $staticUpdateConf[$route];
			switch($updateConf['page_type']){
                case 4:
					if(isset($params[$updateConf['params']]) && $params[$updateConf['params']] !== ''){
					    //$uriPath = '';
				        $basePath = $_SERVER['DOCUMENT_ROOT'].'/'.$this->baseCachePath.'/'.$updateConf['route'];
					    /*$updateConf['is_sub_path'] = trim($updateConf['is_sub_path']);
				        $updateConf['sub_path_param'] = trim($updateConf['sub_path_param']);
                        if($updateConf['is_sub_path'] && $updateConf['sub_path_param']){
					        $pathParam = isset($params[$updateConf['sub_path_param']])?intval($params[$updateConf['sub_path_param']]):0;
                            $dirNum = floor($pathParam/$this->maxFilesOn1Dir);
						    $uriPath .= $dirNum;
				        }*/
						if(is_array($params[$updateConf['params']])){
							foreach($params[$updateConf['params']] as $val){
					            $pathParam = isset($val)?intval($val):0;
                                $dirNum = floor($pathParam/$this->maxFilesOn1Dir);
						        //$uriPath .= $dirNum;
						        $path = str_replace(array('///','//'),array('/','/'),$basePath.'/'.$dirNum);
                                $filePath = $path.'/'.$val.'.html';
						        $this->updateCache($filePath);
							}
						}
						else{
					        $pathParam = isset($params[$updateConf['params']])?intval($params[$updateConf['params']]):0;
                            $dirNum = floor($pathParam/$this->maxFilesOn1Dir);
						    //$uriPath .= $dirNum;
						    $path = str_replace(array('///','//'),array('/','/'),$basePath.'/'.$dirNum);
                            $filePath = $path.'/'.$params[$updateConf['params']].'.html';
						    $this->updateCache($filePath);
						}
				    }
					break;
			}
		}
	}

	public function test(){
	    $d = array(1,2,3);
		var_dump($d);
        array_pop($d);
		var_dump($d);
	}
}
